/*
 * @Author: lsl1201
 * @Date: 2023-08-16 10:21:29
 * @LastEditors: lsl1201 
 * @LastEditTime: 2023-08-18 13:41:07
 */


import { createRouter, createWebHashHistory } from 'vue-router';
import Login from '../views/Login.vue'
import Mainbox from '../views/MainBox.vue'
import NoteFound from '../views/notfound/NoteFound.vue'
import RoutesConfig from './config';
import { useRouterStore } from '../store/useRouterStore';
import { useUserStore } from '../store/useUserStore';

// 导入进度条
import NProgress from 'nprogress'
// css样式
import 'nprogress/nprogress.css'

const routes = [
    {
        path: '/login',
        name: 'login',
        component: Login
    },
    {
        path: '/mainbox',
        name: 'mainbox',
        component: Mainbox
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})
// 路由拦截守卫
router.beforeEach((to, from, next) => {
    // 开启进度条
    NProgress.start()
    const { isGetterRouter } = useRouterStore()
    const { user } = useUserStore()
    // console.log("路由拦截守卫", isGetterRouter)
    if (to.path === '/login') {
        // console.log("当前路径", to.path)
        next()
    } else {
        // 用!user.role代替 !localStorage.getItem('token')
        if (!user.role) {
            router.push('/login')
            next()
        } else {
            // 动态配置路由
            if (!isGetterRouter) {
                // 先清空mainbox包含的路由
                router.removeRoute("mainbox")
                ConfigRouter()
                next({ path: to.fullPath })
            } else {
                next()
            }

        }
    }
})

// 动态配置路由
const ConfigRouter = () => {
    // console.log('动态配置路由')
    const { changeRouter } = useRouterStore()
    // 添加mainbox路由
    router.addRoute({
        path: "/mainbox",
        name: "mainbox",
        component: Mainbox
    })
    RoutesConfig.forEach(item => {
        // console.log(item)
        // 权限判断
        checkPermission(item) && router.addRoute("mainbox", item)
        // console.log("router", router)
    })
    // 重定向
    router.addRoute("mainbox", {
        path: '/',
        redirect: '/index'
    })
    // 404
    router.addRoute("mainbox", {
        path: '/:pathMatch(.*)*',
        name: '404 not found',
        component: NoteFound
    })
    // 改变状态
    changeRouter(true)
}

// 权限判断
const checkPermission = ({ path }) => {
    // useUserStore()获取到的是后端返回的数据,来跟路由配置文件中的数据进行对比,用includes方法
    const { user: { role: { rights } } } = useUserStore()
    // console.log("rights",rights)
    return rights.includes(path)
}

router.afterEach(() => {
    // 关闭进度条
    NProgress.done()
})


export default router